var klassModel = require('../models/klass.js')

const CURRENT_USER_KEY = 'currentUserKey'
const CURRENT_WX_USER_KEY = 'currentWxUserKey'
const USER_EMAIL_KEY = 'userEmailKey'

// 当前所在班级用户角色
const NO_LOGIN = -2  // 用户未登录
const NO_SELECT_CLASS = -3 // 用户没有选择班级
const NORMAL = -1 // 普通用户
const HEAD_TEACHER = 1 // 班主任
const TEACHER = 0  // 任课老师
const PATRIARCH = 100 // 家长

function setCurrentUser(user) {
  wx.setStorageSync(CURRENT_USER_KEY, user)
}

function getCurrentUser() {
  return wx.getStorageSync(CURRENT_USER_KEY)
}

function setCurrentWxUser(wxUser) {
  wx.setStorageSync(CURRENT_WX_USER_KEY, wxUser)
}

function getCurrentWxUser() {
  return wx.getStorageSync(CURRENT_WX_USER_KEY)
}

function setUserEmail(email) {
    wx.setStorageSync(USER_EMAIL_KEY, email)
}

function getUserEmail() {
    return wx.getStorageSync(USER_EMAIL_KEY)
}

/**
 * 获取用户在当前班级的身份
 */
function getRole(klass) {
  var user = getCurrentUser();
  if (user) {
    if (klass) {
      // 先判断是不是老师
      var result = isTeacher(user, klass);
      if(result) {
        return result;
      }

      // 判断是不是家长
      result = isPatriarch(user, klass);
      if (result) {
        return result;
      }

      return { 'role': NORMAL, 'desc': '未绑定' };
    }else {
      return { 'role': NO_SELECT_CLASS, 'desc': '未选择班级' };
    }
  }else {
    return { 'role': NO_LOGIN, 'desc': '未登录' };
  }
}

/**
 * 判断是不是班主任或者老师
 * 
 * param object user, 
 *       object klass
 * 
 * return null 或者 老师身份
 */
function isTeacher(user, klass) {
  var teachers = user.asTeacher;  // array
  if (teachers) {
    var length = teachers.length;
    for(var index = 0; index < length; index++) {
      if(teachers[index].klassSid == klass.sid) {
        if (teachers[index].headTeacher == HEAD_TEACHER) {          
          return { 'role': HEAD_TEACHER, 'desc': '班主任', 'teacher': teachers[index]};
        }else {          
          return { 'role': TEACHER, 'desc': '任课老师', 'teacher': teachers[index] };
        }
      }
    }
  }

  return null;
}

function isPatriarch(user,klass) {
  var patriarchs = user.asRelation;  // array
  if (patriarchs) {
    var length = patriarchs.length;
    var relations = [],desc = '';
    for (var index = 0; index < length; index++) {
      if (patriarchs[index].student.klassSid == klass.sid) {
        relations.push(patriarchs[index])
        if (desc.indexOf(patriarchs[index].student.name) < 0) {
          desc += patriarchs[index].student.name + ' '
        }        
      }
    }

    if (0 < relations.length) {
      return { 'role': PATRIARCH, 'desc': desc, 'relations': relations };
    }
  } 
    
  return null;
}

/**
 * 根据学生sid获取关系对象
 * param string studentSid
 * return object/null
 */
function getRelationByStudentSid(studentSid) {
  var user = getCurrentUser();
  
  var patriarchs = user.asRelation;  // array
  if (patriarchs) {
    var length = patriarchs.length;
    for (var index = 0; index < length; index++) {
      if (patriarchs[index].student.sid == studentSid) {
        return patriarchs[index];
      }
    }
  } 

  return null;
}

/**
 * 将关系与学生数据转换成一个学生对应多个家长的数据模式
 */
function getStudents(relations) {
  if (relations) {
    var length = relations.length,students = []
    for (var index = 0; index < length; index++) {
      hashMap.Remove(relations[index].student.sid)
    }

    var studentIndex = 0
    for (var index = 0;index < length;index++){
      if (hashMap.Get(relations[index].student.sid)) {
        hashMap.Get(relations[index].student.sid).relations.push(makeRelationObject(relations[index]))
      }else {
        students.push(relations[index].student)
        students[studentIndex].relations = []
        students[studentIndex].relations.push(makeRelationObject(relations[index]))
        hashMap.Set(relations[index].student.sid, students[studentIndex])
        studentIndex++
      }
    }

    if (0 < students.length) {
      return students
    }
  }

  return null
}

function makeRelationObject(relation) {
  var result = {}
  result.sid = relation.sid
  result.userSid = relation.userSid
  result.name = relation.name

  return result
}

function getStudentGender(student) {
  if (1 == student.gender) {
    return {'value':1,'name':'女生'}
  }

  return { 'value': 0, 'name': '男生' }
}

function getKlassRoleName(klass) {
  let user = getCurrentUser();

  for (let index=0,length=user.klassRoles.length;index < length; index++) {
    if (klass.sid == user.klassRoles[index].sid) {
      return user.klassRoles[index].roleNames
    }
  }

  return ''
}

var hashMap = {
  Set: function (key, value) { this[key] = value },
  Get: function (key) { return this[key] },
  Contains: function (key) { return this.Get(key) == null ? false : true },
  Remove: function (key) { delete this[key] }
}

/**
 * 显示班级绑定密码
 * 班级创建者同时班级未绑定群关系
 */
function showClassPassword() {
  var klass = klassModel.getKlassUIData()
  var user = getCurrentUser()
  var showPassword = false
  if (klass.creatorSid == user.sid && (null == klass.wxGroupUid || '' == klass.wxGroupUid)) { // 班级创建者，同时未绑定微信群时才显示
    showPassword = true
  }

  return showPassword
}

/**
 * 是否有权限显示班级与微信群绑定的界面
 * @returns {*}
 */
function showWxbindView(klass = null) {
    if (null == klass) {
      klass = klassModel.getKlassUIData()
    }
    var user = getCurrentUser()
    var result = false
    if (klass.creatorSid == user.sid) { // 班级创建者，同时未绑定微信群时才显示
        result = true
    }

    return result
}

/**
 * 检查用户是否有管理权限
 * 班主任和班级创建者有关联权限
 */
function checkUserManager(klass,onlyCreator = false) {
  var user = getCurrentUser()
  if (klass.creatorSid == user.sid) {
    return true
  } else if (true == onlyCreator) {
    return false
  }

  let role = getRole(klass)

  if (HEAD_TEACHER == role.role) {
    return true
  }

  return false
}

module.exports = {
  setCurrentUser: setCurrentUser,
  getCurrentUser: getCurrentUser,
  setCurrentWxUser: setCurrentWxUser,
  getCurrentWxUser: getCurrentWxUser,
  getRole: getRole,
  getRelationByStudentSid: getRelationByStudentSid,
  getStudents: getStudents,
  getStudentGender: getStudentGender,
  NORMAL: NORMAL,
  HEAD_TEACHER: HEAD_TEACHER,
  TEACHER: TEACHER,
  PATRIARCH: PATRIARCH,
  showClassPassword: showClassPassword,
  getKlassRoleName: getKlassRoleName,
  checkUserManager: checkUserManager,
  setUserEmail:setUserEmail,
  getUserEmail:getUserEmail,
  showWxbindView:showWxbindView
}